package com.shaoshaohuo.app.db;

import android.os.Environment;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.SshApplication;
import com.shaoshaohuo.app.entity.AddedService;
import com.shaoshaohuo.app.entity.AddedServiceEntity;
import com.shaoshaohuo.app.entity.BaseUserInfo;
import com.shaoshaohuo.app.entity.CarTypeEntity;
import com.shaoshaohuo.app.entity.CarTypeFirst;
import com.shaoshaohuo.app.entity.CarTypeSecond;
import com.shaoshaohuo.app.entity.EcCategoryEntity;
import com.shaoshaohuo.app.entity.EcCategoryFirst;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.entity.EcCategoryThird;
import com.shaoshaohuo.app.entity.post.BusinessPublish;
import com.shaoshaohuo.app.entity.post.CarInfo;
import com.shaoshaohuo.app.entity.post.PurchasePublished;
import com.shaoshaohuo.app.entity.post.SendGoodsEntity;
import com.shaoshaohuo.app.entity.post.SupplyPublished;
import com.shaoshaohuo.app.utils.FileHelper;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.io.InputStream;
import java.util.List;

/**
 * @author: yusonglin
 * @类 说 明: Db 工具类
 * @version 1.0
 * @创建时间：2015年7月30日 下午12:01:02
 * 
 */
public class DaoUtils {

    private static final int DB_VERSION = 1;
    private static String savePath;
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 11;
    //数据库配置
    private static DbManager.DaoConfig daoConfig;

    //复制db，从raw/tmet.db到/sdcard目录
    public static void init() {
        InputStream is = SshApplication.getContext().getResources().openRawResource(R.raw.tmet);
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            savePath = Environment.getExternalStorageDirectory().getPath();
        } else {
            savePath = SshApplication.getContext().getFilesDir().getPath();
        }

        FileHelper.copyFile(is, savePath + "/tmet.db");


    }


    public static void initDaoConfig() {
        if (savePath == null) {
            init();
        }
        daoConfig = new DbManager.DaoConfig()
                .setDbName("tmet.db")
                .setDbDir(new File(savePath))
                .setDbVersion(DB_VERSION)
                .setAllowTransaction(true)
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                        // TODO: ...
                        // db.addColumn(...);
                        // db.dropTable(...);
                        // ...
                    }
                });
    }



    /**
     * 重建省、市、区县数据库
     * @param areaList
     */
    public static void reloadAllAreas(final List<Area> areaList) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    getDb().dropTable(Area.class);
                    for (Area a : areaList) {
                        getDb().save(a);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 获取数据库
     * @return   DbManager
     */
    private static DbManager getDb() {
        DbManager db = x.getDb(daoConfig);
        return db;
    }

    /**
     * 保存List
     * @param db
     * @param list
     * @param <T>
     * @throws DbException
     */
    private static <T> void saveOrUpdateAll(DbManager db, List<T> list) throws DbException {
        for (T t : list) {
            db.saveOrUpdate(t);
        }
    }

    /**
     * 获取子省、市、区县
     * @param parentId  传入null时，返回省、直辖市
     * @return
     */
    public static List<Area> findSubAreas(String parentId) {
        try {
            List<Area> findAll = getDb().selector(Area.class)
            .where("parentAreaId", "=", parentId)
            .orderBy("id")
            .findAll();//findAll(Selector.from(Province.class));
            /*for (Province province : findAll) {
                province.setCitys(findAllCity(province.getProid()));
            }*/
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    public static Area findArea(String areaId) {
        Area area = null;
        try {
            area = getDb().selector(Area.class)
                    .where("areaId", "=", areaId)
                    .findFirst();
            return area;
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*public static List<City> findAllCity(String proid) {
        try {
            List<City> findAll = getDb().findAll(Selector.from(City.class).where("parentId", "=", proid));
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }*/

    public static void saveCartype(final CarTypeEntity entity) {
        new Thread() {

            public void run() {
                try {
                    List<CarTypeFirst> provincesList = entity.getData().getList();
                    saveOrUpdateAll(getDb(), provincesList);
                    for (CarTypeFirst province : provincesList) {
                        for (CarTypeSecond city : province.getData()) {
                            city.setParentId(province.getTypeid());
                        }
                        saveOrUpdateAll(getDb(), province.getData());
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }

    public static List<CarTypeFirst> findAllCartype() {
        try {
            List<CarTypeFirst> findAll = getDb().selector(CarTypeFirst.class).findAll();
            if (findAll == null) {
            	return null;
            }
            for (CarTypeFirst province : findAll) {
                province.setData(findAllCartype(province.getTypeid()));
            }
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    public static List<CarTypeSecond> findAllCartype(String proid) {
        try {
            List<CarTypeSecond> findAll =
                            getDb().selector(CarTypeSecond.class).where("parentId", "=", proid).findAll();
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    public static void saveUserInfo(final BaseUserInfo entity) {
        // new Thread() {
        // public void run() {
        try {
            // BaseUserInfo baseUserInfo = entity.getBaseinfo();
            getDb().saveOrUpdate(entity);
        } catch (DbException e) {
            e.printStackTrace();
        }
        // };
        // }.start();
    }

    public static void saveAddedService(final AddedServiceEntity entity) {
        new Thread() {

            public void run() {
                try {
                    List<AddedService> provincesList = entity.getData().getList();
                    saveOrUpdateAll(getDb(), provincesList);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }

    public static List<AddedService> findAllAddedService() {
        try {
            List<AddedService> findAll = getDb().selector(AddedService.class).findAll();
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    public static void saveEcCategory(final EcCategoryEntity entity) {
        new Thread() {

            public void run() {
                try {
                    getDb().dropTable(EcCategoryFirst.class);
                    getDb().dropTable(EcCategorySecond.class);
                    getDb().dropTable(EcCategoryThird.class);
                    List<EcCategoryFirst> firstList = entity.getData().getList();
                    saveOrUpdateAll(getDb(), firstList);
                    for (EcCategoryFirst first : firstList) {
                        saveOrUpdateAll(getDb(), first.getSubdata());
                        for (EcCategorySecond second : first.getSubdata()) {
                            saveOrUpdateAll(getDb(), second.getSubdata());
                        }
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }

    public static List<EcCategoryFirst> findAllEcCategoryFirst() {
        try {
            List<EcCategoryFirst> findAll = getDb().selector(EcCategoryFirst.class).findAll();
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    public static List<EcCategorySecond> findAllEcCategorySecond(String bigpid) {
        try {
            List<EcCategorySecond> findAll =
                            getDb().selector(EcCategorySecond.class).where("bigpid", "=", bigpid).findAll();
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * 根据id，获取产品
     * @param id
     * @return
     */
    public static EcCategorySecond findEcCategorySecond(String id) {
        try {
            return getDb().selector(EcCategorySecond.class).where("catid", "=", id).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据 id 获取具体品种
     * @param id
     * @return
     */
    public static EcCategoryThird findEcCategoryThird(String id) {
        try {
            return getDb().selector(EcCategoryThird.class).where("catid", "=", id).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<EcCategoryThird> findAllEcCategoryThird(String pid) {
        try {
            List<EcCategoryThird> findAll = getDb().selector(EcCategoryThird.class).where("pid", "=", pid).findAll();
            return findAll;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    //保存我要买缓存表单
    public static void savePurchasePublished(final PurchasePublished entity) {
        new Thread() {

            public void run() {
                try {
                	getDb().delete(PurchasePublished.class);
                    getDb().save(entity);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }
    //获取我要买缓存表单
    public static PurchasePublished findPurchasePublished() {
        try {
        	PurchasePublished entity = getDb().findFirst(PurchasePublished.class);
            return entity;
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }
    
    //保存我要卖缓存表单
    public static void saveSupplyPublished(final SupplyPublished entity) {
    	new Thread() {
    		
    		public void run() {
    			try {
    				getDb().delete(SupplyPublished.class);
    				getDb().save(entity);
    			} catch (DbException e) {
    				e.printStackTrace();
    			}
    		};
    	}.start();
    }
    //获取我要卖缓存表单
    public static SupplyPublished findSupplyPublished() {
    	try {
    		SupplyPublished entity = getDb().findFirst(SupplyPublished.class);
    		return entity;
    	} catch (Exception e1) {
    		e1.printStackTrace();
    	}
    	return null;
    }
    
    //保存发布商机缓存表单
    public static void saveBusinessPublish(final BusinessPublish entity) {
    	new Thread() {
    		
    		public void run() {
    			try {
    				getDb().delete(BusinessPublish.class);
    				getDb().save(entity);
    			} catch (DbException e) {
    				e.printStackTrace();
    			}
    		};
    	}.start();
    }
    //获取发布商机缓存表单
    public static BusinessPublish findBusinessPublish() {
    	try {
    		BusinessPublish entity = getDb().findFirst(BusinessPublish.class);
    		return entity;
    	} catch (Exception e1) {
    		e1.printStackTrace();
    	}
    	return null;
    }
    
    //保存发货缓存表单
    public static void saveSendGoodsEntity(final SendGoodsEntity entity) {
    	new Thread() {
    		
    		public void run() {
    			try {
    				getDb().delete(SendGoodsEntity.class);
    				getDb().save(entity);
    			} catch (DbException e) {
    				e.printStackTrace();
    			}
    		};
    	}.start();
    }
    //获取发货缓存表单
    public static SendGoodsEntity findSendGoodsEntity() {
    	try {
    		SendGoodsEntity entity = getDb().findFirst(SendGoodsEntity.class);
    		return entity;
    	} catch (Exception e1) {
    		e1.printStackTrace();
    	}
    	return null;
    }
    
    //保存车主车辆配置缓存表单
    public static void saveCarInfo(final CarInfo entity) {
    	new Thread() {
    		
    		public void run() {
    			try {
    				getDb().delete(CarInfo.class);
    				getDb().save(entity);
    			} catch (DbException e) {
    				e.printStackTrace();
    			}
    		};
    	}.start();
    }
    //获取车主车辆配置缓存表单
    public static CarInfo findCarInfo() {
    	try {
    		CarInfo entity = getDb().findFirst(CarInfo.class);
    		return entity;
    	} catch (Exception e1) {
    		e1.printStackTrace();
    	}
    	return null;
    }
}
